<template>
  <div class="login-container">
    <div class="login-card">

      <div class="login-header">
        <h3>学校管理员系统登录</h3>
      </div>

      <el-form ref="loginForm" :model="loginForm" :rules="rules" class="login-form">
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              prefix-icon="el-icon-user"
              placeholder="请输入账号">
          </el-input>
        </el-form-item>

        <el-form-item prop="passWord">
          <el-input
              v-model="loginForm.passWord"
              prefix-icon="el-icon-lock"
              type="password"
              placeholder="请输入密码">
          </el-input>
        </el-form-item>

        <el-button type="primary" class="login-button" @click="handleLogin">登录</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>

import * as Api from "@/api/api"

export default {
  name: 'LoginPage',
  data() {
    return {
      loginForm: {
        username: '',
        passWord: ''
      },
      rules: {
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'}
        ],
        passWord: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 4, message: '密码长度不能少于4个字符', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    const token = localStorage.getItem("token");
    const userInfo = localStorage.getItem("userInfo");
    if (token && userInfo) {
      this.$router.push('/');
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          const res = await Api.login(this.loginForm);
          if (res.code === 200) {
            localStorage.setItem("token", res.token);
            localStorage.setItem("userInfo", JSON.stringify(res.user));
            this.$router.push('/');
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 100%;
  max-width: 400px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 8px;
  font-weight: 600;
}

.login-header p {
  color: #909399;
  font-size: 16px;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  background-color: #409EFF;
  border-color: #409EFF;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
  }
}
</style>